import 'dart:async';
import 'dart:math' as math;
import 'package:FineArt/core/api/class_api.dart';
import 'package:FineArt/core/api/course_api.dart';
import 'package:FineArt/core/api/mqtt_service.dart';
import 'package:FineArt/utils/image_utils.dart';
import 'package:FineArt/utils/log_util.dart';
import 'package:FineArt/utils/platform_util.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:orientation/orientation.dart';
import 'package:photo_view/photo_view.dart';

class StudentCourseView extends StatefulWidget {
  String url;
  int courseid;
  StudentCourseView({this.url, this.courseid});
  static Jump2CourseView(String url, int courseid, context) {
    Navigator.of(context).push(MaterialPageRoute(builder: (context) {
      return StudentCourseView(
        url: url,
        courseid: courseid,
      );
    }));
  }

  @override
  _StudentCourseViewState createState() => _StudentCourseViewState();
}

class _StudentCourseViewState extends State<StudentCourseView> {
  final PhotoViewController _controller = PhotoViewController();
  var _quarterTurns = 0;

  @override
  void initState() {
    super.initState();
    MqttService.mqttClient.subscribe(MqttService.courseTopic(widget.courseid), MqttQos.atLeastOnce);
  }

  @override
  void dispose() {
    _controller.dispose();
    MqttService.mqttClient.unsubscribe(MqttService.courseTopic(widget.courseid));
    super.dispose();
  }

  double _initScale = -1.0;
  double _currentScale;
  Offset _currentOffset;
  double _maxScale = 1.0;

  void _doScaleAndMove(ScaleUpdateDetails e) {
    Offset offset = e.focalPoint - _currentOffset;

    if (offset.dx.abs() > 1.0 || offset.dy.abs() > 1.0) {
      double _dx = offset.dx;
      double _dy = offset.dy;
      Offset o = _controller.position;
      Offset new_off = Offset(o.dx + _dx, o.dy + _dy);
      _controller.position = new_off;
      _currentOffset = e.focalPoint;
    }

    _controller.scale = _currentScale * e.scale;
    if (_controller.scale >= _maxScale) {
      _controller.scale = _maxScale;
      return;
    }
    if (_controller.scale <= _initScale) {
      _controller.scale = _initScale;
      return;
    }
  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: Colors.black,
      body: Container(
        height: size.height,
        width: size.width,
        child: GestureDetector(
          onScaleUpdate: (e) => {_doScaleAndMove(e)},
          onScaleStart: (e) {
            if (_initScale == -1.0) {
              _initScale = _controller.scale;
            }
            _currentScale = _controller.scale;
            _currentOffset = e.focalPoint;
          },
          child: ClipRect(
            child: PhotoView(
              controller: _controller,
              imageProvider: CachedNetworkImageProvider(widget.url),
              maxScale: _maxScale,
              initialScale: PhotoViewComputedScale.contained,
              minScale: PhotoViewComputedScale.contained,
              enableRotation: false,
              disableGestures: true,
              onTapUp: (c, d, v) => {LogUtil.d("==>onTapUp")},
              scaleStateChangedCallback: (v) =>
                  {LogUtil.d("==>scaleStateChangedCallback")},
              loadingBuilder: (context, event) => Center(
                child: Container(
                  width: 30.0,
                  height: 30.0,
                  child: CircularProgressIndicator(
                    value: event == null
                        ? 0
                        : event.cumulativeBytesLoaded /
                            event.expectedTotalBytes,
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
      // floatingActionButton: FloatingActionButton(
      //   child: Text("旋转"),//const Icon(Icons.rotate_right),
      //   onPressed: _rotateRight90Degrees,
      // ),
    );
  }

  void _rotateRight90Degrees() {
    // Set the rotation to either 0, 90, 180 or 270 degrees (value is in radians)
    _quarterTurns = _quarterTurns == 3 ? 0 : _quarterTurns + 1;
    _controller.rotation = math.pi / 2 * _quarterTurns;
  }
}
